﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;
using Think9.Services.Flow;
using Think9.Services.Table;

namespace Think9.Controllers.Basic
{
    [Area("SysTable")]
    public class TbBasicController : BaseController
    {
        private ComService ComService = new ComService();
        private SortService SortService = new SortService();
        private TbBasicService TbBasicService = new TbBasicService();
        private TbBasic2Service TbBasic2Service = new TbBasic2Service();
        private FlowService Flowervice = new FlowService();
        private IndexDateType IndexDtaeTypeService = new IndexDateType();

        public ActionResult Add01()
        {
            ViewBag.TbSortList = new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_table"), "SortID", "SortName");
            ViewBag.DtaeTypeList = IndexDtaeTypeService.GetIndexDtaeTypeList();
            ViewBag.IndexSortList = new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_index"), "SortID", "SortName");
            ViewBag.ClassID = "CAT_table";
            return View();
        }

        public ActionResult Edit01(string tbid)
        {
            ViewBag.TbSortList = new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_table"), "SortID", "SortName");

            var model = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
            if (model != null)
            {
                var mflow = Flowervice.GetByWhereFirst("where FlowId=@FlowId", new { FlowId = model.FlowId });
                model.FlowType = mflow == null ? "" : mflow.FlowType;
                model.EditUser = mflow == null ? "" : mflow.EditUser;
                model.EditUser_Exa = CommonSelectService.GetNameStrByIdStr(model.EditUser, "1");

                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        public ActionResult Edit02(string tbid)
        {
            var model = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
            if (model != null)
            {
                var mTbBasic2 = TbBasic2Service.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
                model.InType = mTbBasic2 == null ? "0" : mTbBasic2.InType;

                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        public ActionResult TbLimits(string tbid)
        {
            TbBasicEntity model = TbBasicService.GetByWhereFirst("where TbId='" + tbid + "'");
            if (model == null)
            {
                return Json("录入表对象为空！");
            }
            else
            {
                if (model.TbType == "1")
                {
                    List<ControlEntity> list = new List<ControlEntity>();
                    FlowEntity mFlow = Flowervice.GetByWhereFirst("where FlowId='" + model.FlowId + "'");
                    if (mFlow != null)
                    {
                        mFlow.EditUser_Exa = CommonSelectService.GetNameStrByIdStr(mFlow.EditUser, "1");
                        mFlow.ManageUser_Exa = CommonSelectService.GetNameStrByIdStr(mFlow.ManageUser, "1");
                        mFlow.ManageUser2_Exa = CommonSelectService.GetNameStrByIdStr(mFlow.ManageUser2, "1");
                        mFlow.QueryUser_Exa = CommonSelectService.GetNameStrByIdStr(mFlow.QueryUser, "1");
                        mFlow.QueryUser2_Exa = CommonSelectService.GetNameStrByIdStr(mFlow.QueryUser2, "1");

                        ViewBag.List = list;
                        ViewBag.SearchMode = string.IsNullOrEmpty(mFlow.SearchMode) ? "11" : mFlow.SearchMode;

                        return View(mFlow);
                    }
                    else
                    {
                        return Json("流程对象为空！");
                    }
                }
                else
                {
                    return Json("无需为子表设置！");
                }
            }
        }

        public ActionResult TbAtt(string tbid)
        {
            TbBasicEntity model = TbBasicService.GetByWhereFirst("where TbId='" + tbid + "'");
            if (model == null)
            {
                return Json("录入表对象为空！");
            }
            else
            {
                if (model.TbType == "1")
                {
                    List<ControlEntity> list = new List<ControlEntity>();
                    FlowEntity mFlow = Flowervice.GetByWhereFirst("where FlowId='" + model.FlowId + "'");
                    if (mFlow != null)
                    {
                        return View(mFlow);
                    }
                    else
                    {
                        return Json("流程对象为空！");
                    }
                }
                else
                {
                    return Json("无需为子表设置！");
                }
            }
        }

        public ActionResult TbBut(string tbid)
        {
            TbBasicEntity model = TbBasicService.GetByWhereFirst("where TbId='" + tbid + "'");
            if (model == null)
            {
                return Json("录入表对象为空！");
            }
            else
            {
                model.TbId = tbid;
                if (model.TbType == "1")
                {
                    TbBasicService.GetTbButton(tbid, ref model);
                    return View(model);
                }
                else
                {
                    return Json("无需为子表设置！");
                }
            }
        }

        public ActionResult EditTbBut(string tbid, TbBasicEntity model)
        {
            try
            {
                TbBasicService.UpTbButton(tbid, model);

                string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                Record.AddRecord(userid, tbid, "编辑录入表页面按钮");

                return Json(SuccessTip("操作成功"));
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        public ActionResult EditTbLimits(FlowEntity model, string fwid)
        {
            string err = "";

            try
            {
                if (fwid.StartsWith("fw_"))
                {
                    model.EditUser = "";
                }

                string where = "where FlowId='" + fwid + "'";
                string updateFields = "EditUser,ManageUser,ManageUser2,SearchMode";

                err = Flowervice.UpdateByWhere(where, updateFields, model) > 0 ? "" : "编辑失败";

                if (string.IsNullOrEmpty(err))
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, fwid.Replace("bi_", "tb_").Replace("fw_", "tb_"), "编辑录入表权限");
                    return Json(SuccessTip("操作成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        public ActionResult EditTbAtt(FlowEntity model, string fwid)
        {
            string err = "";

            try
            {
                string where = "where FlowId='" + fwid + "'";
                string updateFields = "FlowAttachment,FlowAttachment2,FlowAttachment3";

                err = Flowervice.UpdateByWhere(where, updateFields, model) > 0 ? "" : "编辑失败";

                if (string.IsNullOrEmpty(err))
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, fwid.Replace("bi_", "tb_").Replace("fw_", "tb_"), "编辑录入表公共附件设置");
                    return Json(SuccessTip("操作成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        public ActionResult RecordList(string tbid)
        {
            ViewBag.tbid = tbid;

            return View();
        }

        public ActionResult GetRecordList(PageInfoEntity pageInfo, string tbid, string key)
        {
            RecordSetService RecordSetService = new RecordSetService();
            RecordSetEntity model = new RecordSetEntity();

            pageInfo.field = "OperateTime";
            pageInfo.order = "desc";

            key = string.IsNullOrEmpty(key) ? "" : key;
            tbid = string.IsNullOrEmpty(tbid) ? "" : tbid;

            string where = "where ObjectId = '" + tbid + "' ";

            if (key != "")
            {
                where += " and (Info like @Info) ";
                model.Info = string.Format("%{0}%", key);
            }

            long total = 0;
            IEnumerable<dynamic> list = RecordSetService.GetPageByFilter(ref total, model, pageInfo, where);

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        [HttpPost]
        public ActionResult Edit01(TbBasicEntity model, string fwid)
        {
            string err = "";
            try
            {
                string where = "where TbId='" + model.TbId + "'";
                string updateFields = "TbSortId,TbName,OrderNo,TbExplain";

                model.TbSortId = model.TbSortId == null ? "" : model.TbSortId;
                err = TbBasicService.UpdateByWhere(where, updateFields, model) > 0 ? "" : "编辑失败";
                if (string.IsNullOrEmpty(err))
                {
                    if (fwid.StartsWith("bi_"))
                    {
                        FlowEntity mflow = new FlowEntity();
                        mflow.FlowId = fwid;
                        mflow.EditUser = model.EditUser;

                        where = "where FlowId='" + fwid + "'";
                        updateFields = "EditUser";

                        err = Flowervice.UpdateByWhere(where, updateFields, mflow) > 0 ? "" : "编辑失败";
                    }
                }

                if (string.IsNullOrEmpty(err))
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, model.TbId, "编辑录入表");

                    return Json(SuccessTip("操作成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult Edit02(TbBasicEntity model)
        {
            string err = "";
            string where = "where TbId='" + model.TbId + "'";
            string updateFields = "TbName,OrderNo,TbExplain";

            model.TbSortId = model.TbSortId == null ? "" : model.TbSortId;
            err = TbBasicService.UpdateByWhere(where, updateFields, model) > 0 ? "" : "编辑失败";
            if (string.IsNullOrEmpty(err))
            {
                updateFields = "InType";
                TbBasic2Entity mTbBasic2 = new TbBasic2Entity();
                mTbBasic2.TbId = model.TbId;
                mTbBasic2.InType = model.InType;
                err = TbBasic2Service.UpdateByWhere(where, updateFields, mTbBasic2) > 0 ? "" : "编辑失败";
            }

            if (string.IsNullOrEmpty(err))
            {
                string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                Record.AddRecord(userid, model.TbId, "编辑录入表");

                return Json(SuccessTip("操作成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        public ActionResult Add02()
        {
            ViewBag.TbList = TbBasicService.GetByWhere("where TbType='1'", null, "TbId,TbName");
            ViewBag.selectNumber = TbBasicService.GetGridLineNumber();
            ViewBag.DtaeTypeList = IndexDtaeTypeService.GetIndexDtaeType();
            return View();
        }

        [HttpPost]
        public ActionResult AddTable(TbBasicEntity model)
        {
            string err = "";
            string str = "#login#home#";
            string tbid = model.TbId.ToLower();
            if (str.ToLower().Contains("#" + model.TbId.ToLower() + "#"))
            {
                err = "编码不能为以下关键字：" + str.Replace("#", " ");
                var result = ErrorTip(err);
                return Json(result);
            }

            for (int i = 1; i <= 25; i++)
            {
                if (model.TbId.ToLower().EndsWith("v" + i.ToString()))
                {
                    err = "编码不能以：" + "v" + i.ToString() + "结尾";
                    var result = ErrorTip(err);
                    return Json(result);
                }
            }

            if (model.BInfo == "1" && string.IsNullOrEmpty(model.EditUser))
            {
                var result = ErrorTip("请选择可编辑用户");
                return Json(result);
            }

            try
            {
                string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                string where = "where TbId=@TbId";
                if (ComService.GetTotal("TbBasic", where, new { TbId = "tb_" + model.TbId }) > 0)
                {
                    var result = ErrorTip("添加失败!已存在相同编码");
                    return Json(result);
                }
                else
                {
                    err = TbBasicService.AddTable(model, userid);
                }

                if (err == "")
                {
                    if (!model.TbId.StartsWith("tb_"))
                    {
                        model.TbId = "tb_" + tbid;
                    }

                    Record.AddRecord(userid, model.TbId, "新建录入表");
                    return Json(SuccessTip("添加成功,将进入下一步为录入表添加录入指标"));
                }
                else
                {
                    return Json(ErrorTip("添加失败：" + err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip("添加失败：" + ex.Message));
            }
        }

        [HttpPost]
        public ActionResult AddTable2(TbBasicEntity model, IEnumerable<TbIndexEntity> list)
        {
            string err = "";
            try
            {
                string where = "where TbId=@TbId";
                if (ComService.GetTotal("TbBasic", where, new { TbId = "tb_" + model.TbId }) > 0)
                {
                    var result = ErrorTip("添加失败!已存在相同编码");
                    return Json(result);
                }
                else
                {
                    err = TbBasicService.AddTable(model, list);
                }

                if (err == "")
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, model.TbId, "新建录入表");

                    return Json(SuccessTip("操作成功"));
                }
                else
                {
                    return Json(ErrorTip("操作失败" + err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip("操作失败" + ex.Message));
            }
        }

        [HttpPost]
        public ActionResult GetCreatDBStr(string tbid)
        {
            if (!tbid.StartsWith("tb_"))
            {
                tbid = "tb_" + tbid;
            }
            TbBasicEntity model = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
            if (model != null)
            {
                string ParentId = model.ParentId;
                string type = ParentId == "" ? "1" : "2";
                string sql = ComService.GetCreatDBStr(tbid, type, model.FlowId);

                //string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                //Record.AddRecord(userid, tbid, "创建数据表");

                var result = SuccessTip("操作成功", sql);
                return Json(result);
            }
            else
            {
                return Json(ErrorTip("操作失败，录入表不存在"));
            }
        }

        [HttpPost]
        public ActionResult CreatTableDB(string tbid)
        {
            if (!ComService.TabExists(tbid))
            {
                TbBasicEntity model = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
                if (model != null)
                {
                    string ParentId = model.ParentId;
                    string type = ParentId == "" ? "1" : "2";
                    string sql = ComService.GetCreatDBStr(tbid, type, model.FlowId);
                    ComService.ExecuteSql(sql);
                }

                if (ComService.TabExists(tbid))
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "创建数据表");

                    return Json(SuccessTip("操作成功"));
                }
                else
                {
                    return Json(ErrorTip("操作失败"));
                }
            }
            else
            {
                return Json(ErrorTip("数据表已存在"));
            }
        }

        [HttpPost]
        public ActionResult CreatDB(string sql, string tbid)
        {
            ComService.ExecuteSql(sql);

            if (!tbid.StartsWith("tb_"))
            {
                tbid = "tb_" + tbid;
            }

            if (ComService.TabExists(tbid))
            {
                string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                Record.AddRecord(userid, tbid, "创建数据表");

                return Json(SuccessTip("操作成功"));
            }
            else
            {
                return Json(ErrorTip("操作失败"));
            }
        }

        [HttpPost]
        public ActionResult GetModel(string tbid)
        {
            var model = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });
            TbBasicService.GetCount(tbid, ref model);

            var menuJson = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            var result = SuccessTip("操作成功", menuJson);

            return Json(result);
        }

        public ActionResult DeletTbAll(string tbid)
        {
            if (Think9.Services.Base.Configs.GetValue("IsDemo") == "true")
            {
                return Json(ErrorTip("演示模式下不能删除录入表！"));
            }
            else
            {
                string err = TbBasicService.DeletTbAll(tbid);

                if (err == "")
                {
                    string userid = CurrentUser == null ? "un_defined" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "删除录入表");

                    return Json(SuccessTip("删除成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
        }

        public JsonResult GetLineNumber(int iCount)
        {
            List<TbIndexEntity> list = new List<TbIndexEntity>();

            for (int i = 1; i <= iCount; i++)
            {
                list.Add(new TbIndexEntity { IndexId = "v" + i.ToString(), IndexName = "列" + i.ToString(), IndexNo = i, ColumnWith = 150, DataType = "" });
            }

            var result = new { code = 0, msg = "", count = list.Count, data = list };

            return Json(result);
        }
    }
}